package com.webbase.control.controller.systemManager;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.webbase.control.common.annotation.CurrentUser;
import com.webbase.control.common.result.Result;
import com.webbase.control.pojo.User;
import com.webbase.control.pojo.UserRole;
import com.webbase.control.service.UserRoleService;
import com.webbase.control.service.UserService;
import com.webbase.control.util.DateUtil;
import com.webbase.control.util.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(value = "用户管理")
@RestController
@RequestMapping("userMgr")
public class UserMgrController {

    @Autowired
    private UserService  userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private MD5 md5;

    @ApiOperation(value = "获取所有用户")
    @GetMapping("getList")
    @RequiresAuthentication
    @ResponseBody
    @CrossOrigin
    public Result<?> getList(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_del_flag",1);
        List<User> list = userService.list(wrapper);
        return new Result<>().success().put(list);
    }

    @ApiOperation(value = "删除用户")
    @PostMapping("del")
    @RequiresAuthentication
    @ResponseBody
    @CrossOrigin
    public Result<?> getList(@RequestBody Map map){
        Object res = map.get("user");
        User user = JSON.parseObject(JSON.toJSONString(res),User.class);
        user.setUserDelFlag(0);
        userService.updateById(user);
        return new Result<>().success();
    }

    @ApiOperation(value = "更新用户信息")
    @PostMapping("update")
    @RequiresAuthentication
    @ResponseBody
    @CrossOrigin
    public Result<?> update(@RequestBody Map map){
        Object res = map.get("user");
        User user = JSON.parseObject(JSON.toJSONString(res),User.class);

        user.setUserUpdateTime(DateUtil.formatTime(new Date()));
        String pass =md5.encrypt(user.getUserPassword());
        user.setUserPassword(pass);
        userService.updateById(user);
        return new Result<>().success();
    }

    @ApiOperation(value = "添加用户")
    @PostMapping("add")
    @RequiresAuthentication
    @ResponseBody
    @CrossOrigin
    public Result<?> add(@RequestBody Map map){
        Object res = map.get("user");
        User user = JSON.parseObject(JSON.toJSONString(res),User.class);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account",user.getUserAccount());
        int count = userService.count(wrapper);
        if(count > 0){
            return new Result<>().error(500,"该用户已存在！");
        }
        String pass =md5.encrypt(user.getUserPassword());
        user.setUserPassword(pass);
        user.setUserDelFlag(1);
        user.setUserState(1);
        user.setUserCreatetime(DateUtil.formatTime(new Date()));
        user.setUserUpdateTime(DateUtil.formatTime(new Date()));
        userService.save(user);
        return new Result<>().success();
    }

    @ApiOperation(value = "设置用户角色")
    @PostMapping("setRole")
    @RequiresAuthentication
    @ResponseBody
    @CrossOrigin
    public Result<?> setRole(@RequestBody Map map){
        Object res = map.get("userRole");
        UserRole userRole = JSON.parseObject(JSON.toJSONString(res),UserRole.class);
        //查询是否存在 存在更新 否则插入
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userRole.getUserId());
        UserRole userRole1 = userRoleService.getOne(wrapper);
        if(userRole1 != null){
            UserRole userRole2 = new UserRole();
            userRole2.setId(userRole1.getId());
            userRole2.setUserId(userRole.getUserId());
            userRole2.setRoleId(userRole.getRoleId());
            userRoleService.updateById(userRole2);
        }else{
            userRoleService.save(userRole);
        }
        return new Result<>().success();
    }

    @PostMapping("setUserPerson")
    @RequiresAuthentication
    @ResponseBody
    @CrossOrigin
    public  Result<?> setUserPerson(@RequestBody Map map){
        Object res = map.get("user");
        User user = JSON.parseObject(JSON.toJSONString(res),User.class);
        user.setUserUpdateTime(DateUtil.formatTime(new Date()));
        userService.updateById(user);
        return new Result().success().put(user);
    }

    @PostMapping("setAvatar")
    @ResponseBody
    @CrossOrigin
    //@RequiresAuthentication
    public Result<?> setAvatar(MultipartFile file, @CurrentUser User user) throws IOException {
        byte[] byt = null;
        try {
            byt = new byte[file.getInputStream().available()];
            file.getInputStream().read(byt);
            String res = new BASE64Encoder().encodeBuffer(byt);
            user.setUserImg("data:image/jpeg;base64,"+res);
            userService.updateById(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return  new Result().success().put(user);
    }

    @PostMapping("setUserPass")
    @ResponseBody
    @CrossOrigin
    @RequiresAuthentication
    public Result<?> setUserPass(@CurrentUser User user,@RequestBody Map map){
        try {
            String oldPass = (String) map.get("oldPass");
            String newPass = (String) map.get("newPass");
            if(!oldPass.equals(user.getUserPassword())){
                return new Result<>().error(403,"旧密码输入错误");
            }else if(oldPass.equals(newPass)){
                return new Result<>().error(406,"新密码不能与旧密码相同");
            } else{
                user.setUserPassword(newPass);
                userService.updateById(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result<>().success().put(user);
    }
}
